<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class MessageController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'Message';

        $this->defaultOrder = [
            ['filed' => 'created_at', 'order' => 'DESC'],
        ];
    }

    /**
     * 操作
     */
    public function handle(Request $request)
    {
        $param = $request->all();
        if (empty($param['id']) && empty($param['ids'])) {
            return api_response(self::STATUS_ERROR, self::NOT_PARAM, '');
        }
        if (!isset($param['status'])) {
            return api_response(self::STATUS_ERROR, '操作类型(status)不能为空', self::NOT_PARAM);
        }

        DB::beginTransaction();
        try {
            $className = '\\App\\Models\\' . $this->modelName;
            $model = new $className;
            if (isset($param['ids']) && $param['ids']) {
                $ids = (array)$param['ids'];
            } else {
                $ids = (array)$param['id'];
            }
            foreach ($ids as $id) {
                $info = $model->where('id', $id)->select(['*'])->first();
                if (!$info) {
                    DB::rollBack();
                    return api_response(self::STATUS_ERROR, '不存在', '');
                }
                $info->status = $param['status'];
                $result = $info->save();
                if ($result === false) {
                    DB::rollBack();
                    return api_response(self::STATUS_ERROR, '失败', '');
                }
            }

            DB::commit();
            return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, '');
        } catch (Exception $e) {
            DB::rollBack();
            return api_response(self::STATUS_ERROR, '失败', $e->getMessage());
        }
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['status']) && strlen($param['status']) > 0) {
            $where[] = ['status', '=', $param['status']];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = $param['range_date'];
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = ['created_at', '>=', $startTime];
            $where[] = ['created_at', '<=', $endTime];
        }

        return $where;
    }
}
